package com.xu.t1.middleware.online;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 管理维护在线人数状态的工具类
 *
 * @author xu
 *
 */

@Component
public class OnlineUserManager {


    @Autowired
    private StringRedisTemplate redisTemplate;


    // 设置在线时间 TTL：1分钟
    private static final Duration ONLINE_TTL = Duration.ofMinutes(1);


    // 用于向redis发送添加或者更新用户在线信息
    public void refreshUserOnline(String clientId, String serverId) {
        // Key：用于 Redis 过期监听（包含 clientId 和 serverId）
        String redisKey = "online:" + clientId + ":" + serverId;

        // 设置 1分钟 TTL（如果已存在会自动刷新）
        redisTemplate.opsForValue().set(redisKey, "", ONLINE_TTL);

        // 添加到总在线用户集合
        redisTemplate.opsForSet().add("online:users", clientId);

        // 添加到对应服务器的在线用户集合
        redisTemplate.opsForSet().add("online:servers:" + serverId, clientId);
    }

    // 维护在线人数信息
    public void removeUserOnline(String online, String clientId, String serverId) {

        // 从总在线用户集合中移除该用户
        redisTemplate.opsForSet().remove(online + ":users", clientId);

        // 从该服务器的在线用户集合中移除该用户
        redisTemplate.opsForSet().remove(online + ":servers:" + serverId, clientId);


    }


    // 获取在线人数信息
    public Map<String, Object> getOnlineStats() {
        // 获取总在线用户数
        Long totalOnline = redisTemplate.opsForSet().size("online:users");

        // 获取所有服务器的在线用户数
        Set<String> serverKeys = redisTemplate.keys("online:servers:*");
        Map<String, Integer> serverMap = new HashMap<>();

        if (!serverKeys.isEmpty()) {
            for (String key : serverKeys) {
                String serverId = key.substring("online:servers:".length());
                Long serverCount = redisTemplate.opsForSet().size(key);
                serverMap.put(serverId, serverCount != null ? serverCount.intValue() : 0);
            }
        }

        Map<String, Object> result = new HashMap<>();
        result.put("total", totalOnline != null ? totalOnline.intValue() : 0);
        result.put("servers", serverMap);
        return result;
    }

    // 获取全在线人数
    public Integer getOnlineTotal() {
        Map<String, Object> stats = getOnlineStats();
        Object total = stats.get("total");

        if (total instanceof Integer) {
            return (Integer) total;
        } else return 0;
    }


    // 获取指定服务器在线人数
    public int getServerOnlineCount(String serverId) {
        Map<String, Object> stats = getOnlineStats();
        Object serversObj = stats.get("servers");

        if (serversObj instanceof Map<?, ?> rawMap) {
            Map<String, Integer> serverMap = new HashMap<>();
            for (Map.Entry<?, ?> entry : rawMap.entrySet()) {
                if (entry.getKey() instanceof String && entry.getValue() instanceof Integer) {
                    serverMap.put((String) entry.getKey(), (Integer) entry.getValue());
                }
            }
            return serverMap.getOrDefault(serverId, 0);
        }
        return 0;
    }


    // 查看历史在线人数
    public Integer getOnlineHistory(String serverId, int secondsAgo) {
        String key = "online:history" + serverId;
        String result = redisTemplate.opsForList().index(key, secondsAgo);
        if (result == null) {
            return 0;
        }
        return Integer.parseInt(result);
    }
}